package com.gd.iot.energy.filter;

import cn.hutool.json.JSONUtil;
import com.gd.iot.energy.annotation.SystemLogRecordMonitor;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.po.superadmin.LogPOWithBLOBs;
import com.gd.iot.energy.pojo.superadmin.dto.AdminDTO;
import com.gd.iot.energy.service.superadmin.LogService;
import com.gd.iot.energy.util.CurrentUserUtil;
import com.gd.iot.energy.util.CustomRequestUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Description
 *
 * @author kris
 * @date Created at 9:22 下午 2020/8/6
 */
@Component
@Aspect
public class SystemLogAspect {
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.gd.iot.energy.annotation.SystemLogRecordMonitor)")
    public void pointCut() {

    }

    @Around(value = "pointCut()  && @annotation(systemLogRecordMonitor)")
    public Object recordSystemLog(ProceedingJoinPoint joinPoint, SystemLogRecordMonitor systemLogRecordMonitor) throws Throwable {

        AdminDTO userInfo = CurrentUserUtil.getUserInfo();
        Object result = joinPoint.proceed(joinPoint.getArgs());

        //记录日志
        String operation = systemLogRecordMonitor.value();

        if(userInfo==null) {
            userInfo = CurrentUserUtil.getUserInfo();
        }

        LogPOWithBLOBs logPOWithBLOBs = new LogPOWithBLOBs();
        logPOWithBLOBs.setCreateDate(new Date());
        logPOWithBLOBs.setModifyDate(new Date());
        logPOWithBLOBs.setIsDel(SystemConsts.BooleanEnum.FALSE.value);
        logPOWithBLOBs.setEnergyType(SystemConsts.EnergyTypeEnum.WATER.value);
        logPOWithBLOBs.setIp(CustomRequestUtil.getRequestIp());
        logPOWithBLOBs.setOperation(operation);
        logPOWithBLOBs.setParameter(JSONUtil.toJsonStr(joinPoint.getArgs()));
        if(userInfo!=null) {
            logPOWithBLOBs.setOperatorId(userInfo.getOperatorId());
            logPOWithBLOBs.setOperator(userInfo.getUsername());
        }
        logService.saveLog(logPOWithBLOBs);
        return result;
    }
}

